import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '../store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/column/:id',
    name: 'Column',
    component: () => import('@/views/Column.vue')
  },
  {
    path: '/posts/:id',
    name: 'Posts',
    component: () => import('@/views/Posts.vue')
  },
  {
    path: '/posts/create',
    name: 'PostsCreate',
    component: () => import('@/views/PostsCreate.vue'),
    meta: {
      requiredLogin: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const { user, token } = store.state
  const { requiredLogin } = to.meta
  if (user.isLogin) {
    next()
  } else {
    if (token) {
      store
        .dispatch('getUserInfo')
        .then(() => {
          next()
        })
        .catch(() => {
          store.commit('logout')
          next('/login')
        })
    } else {
      if (requiredLogin) {
        next('/login')
      } else {
        next()
      }
    }
  }
})

export default router
